package JavaSE.CODE.javaThread.concurrent;

public class TRRace implements Runnable {
    //注意：只有Runnable的（实现类）级别的变量才能被多线程共享
    String winner = null;

    @Override
    public void run() {
        //方法级别的变量，每个线程各自拥有一套，互不影响
        int steps = 100;//每个角色距离终点还剩的距离
        while(steps>=0){//只要这个角色还没到终点，就继续跑；包含0是因为要把0传进判断方法才能宣告结束
            if(winner!=null) break;//如果已经有赢家了了，就结束（break）了

            //模拟兔子休息
            if(Thread.currentThread().getName().equals("兔子") && steps%50==0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //没有gameover，往前跑
            if(Thread.currentThread().getName().equals("兔子"))
                steps-=5;
            else
                steps--;

            System.out.println(Thread.currentThread().getName() + "距离终点还剩 " + steps + " 步");
            gameover(steps);//检查一下有没有gameover
        }
    }

    public void gameover(int steps) {
        if (steps <= 0) {
            //将当前线程的名字打印出来
            winner = Thread.currentThread().getName();
            System.out.println("The winner is " + winner);
        }
    }

    public static void main(String[] args) {
        TRRace trRace = new TRRace();
        new Thread(trRace,"兔子").start();
        new Thread(trRace,"乌龟").start();

    }

}
